const inquirer = require('inquirer')
const shell = require('shelljs')
const fs = require('fs-extra')
const print = require('../../lib/print')
const utils = require('../../lib/utils')
const xcodebuild = require('../../lib/xcodebuild')

var build_argument = {
    target: '',
    targetValue: '',
    scheme: '',
    configuration: '',
    sdk: '',
    buildDir: ''
}

module.exports = async function() {
    try {
        // 1.
        let params = await initParams()
        // 2.
        build_argument.configuration = params.configuration
        build_argument.buildDir = `${params.projectPath}/BUILD_DIR`
        settingArgument(params.projectPath)
        // 
        shell.cd(params.projectPath)
        // 3. 编译模拟器
        build_argument.sdk = 'iphonesimulator'
        await xcodebuild.buildCommand(build_argument)
        // 4. 编译真机
        build_argument.sdk = 'iphoneos'
        await xcodebuild.buildCommand(build_argument)
        // 5. 合并 framework
        mergeFramework(params, build_argument)
    } catch (error) {
        print.errorLog(error)
    }
}

/*
 * 键盘输入部分，获取自定义信息
 */
function initParams() {
    let promptList = [
        {
            type: 'input',
            message: '请输入 framework 工程路径：',
            name: 'projectPath',
            default: process.cwd()
        },
        {
            type: 'list',
            message: '请选择编译环境：',
            name: 'configuration',
            choices: ['Debug', 'Release']
        }
    ]
    return new Promise((resolve, reject) => {
        inquirer.prompt(promptList)
            .then(answer => {
                resolve(answer)
            })
    })
}

/*
 * 设置 build_argument
 * 从给点的项目路径，查找启动文件
 */
function settingArgument(projectPath) {
    shell.ls(projectPath).some(element => {
        let stat = fs.statSync(`${projectPath}/${element}`)
        if (stat.isDirectory() && (element.includes('.xcworkspace') || element.includes('xcodeproj'))) {
            build_argument.targetValue = element
            build_argument.scheme = element.split('.')[0]
            if (element.includes('.xcworkspace')) {
                build_argument.target = 'workspace'
            }else {
                build_argument.target = 'project'
            }
            return true
        }
    })
    if (build_argument.target.length == 0) {
        throw '无可用 xcworkspace 或  xcodeproj'
    }
}

/*
 * 合并模拟器与真机的 framework 文件
 */
function mergeFramework({projectPath}, {scheme, configuration, buildDir}) {
    // 模拟器 framework 文件
    let simulatorFilePath = `${buildDir}/${configuration}-iphonesimulator/${scheme}.framework/${scheme}`
    // 真机 framework 文件夹
    let osFrameworkPath = `${buildDir}/${configuration}-iphoneos/${scheme}.framework`
    // 真机 framework 文件
    let osFilePath = `${osFrameworkPath}/${scheme}`
    // 合并文件夹
    let mergePath = `${projectPath}/MergeFramework`
    // 合并后的 framework 文件
    let mergeFilePath = `${mergePath}/${scheme}.framework/${scheme}`

    // 创建合并文件夹
    if (!fs.existsSync(mergePath)) {
        fs.mkdirSync(mergePath)
    }
    // 复制一份真机 framework 到合并目录下
    let cp_cmd = `cp -r -f ${osFrameworkPath} ${mergePath}`
    shell.exec(cp_cmd)
    // 合并 framework
    let merge_cmd = `lipo -create ${simulatorFilePath} ${osFilePath} -output ${mergeFilePath}`
    console.log(merge_cmd)
    shell.exec(merge_cmd)
    print.successLog('** Merge Success **')
    // 删除 build_dir 临时目录
    shell.rm('-r', buildDir)
}

